/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-12-03 16:37:56
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-12-04 17:52:22
 * @FilePath: /mallSystem/app/service/merchant_service.go
 * @Description:
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package service

import (
	"xiaoquio/web/app/dto"
	"xiaoquio/web/core/utils"
	"xiaoquio/web/middleware"
	"xiaoquio/web/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type MerchantService struct {
	db *gorm.DB
}

// 构造函数 注入数据库链接
func NewMerchantService() *MerchantService {
	return &MerchantService{}
}

func (s *MerchantService) GetMerchantInfoByID(c *gin.Context, memberID string) (*dto.MerchantDTO, error) {
	//获取数据库链接
	db, err := middleware.GetDB(c, "datas")

	if err != nil {
		utils.ResponseNilData(c, 500, "数据库链接失败！")
		return nil, err
	}

	var merchant model.Merchants
	if err := db.First(&merchant, "id = ?", memberID).Error; err != nil {
		return nil, err

	}
	memberDTO := dto.GetMerchantDTO(merchant)
	return &memberDTO, nil

}

func (s *MerchantService) FindAllMerchant(c *gin.Context, page, pageSize int) ([]dto.MerchantDTO, int64, error) {

	// 获取数据库链接
	db, err := middleware.GetDB(c, "datas")

	if err != nil {
		utils.ResponseNilData(c, 500, "数据库链接失败！")
		return nil, 0, err
	}

	var members []model.Merchants

	var total int64

	offset := (page - 1) * pageSize
	if err := db.Model(&model.Merchants{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 如果分页超出范围，直接返回空数据，减少查询开销
	if page > int(total)/pageSize+1 {
		// 没有数据可以返回，直接返回空数据
		return nil, total, nil
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&members).Error; err != nil {
		utils.ResponseNilData(c, 500, "数据查询失败！")
		return nil, 0, err
	}

	var memberDTOs []dto.MerchantDTO
	for _, m := range members {
		memberDTOs = append(memberDTOs, dto.GetMerchantDTO(m))
	}
	return memberDTOs, total, nil
}
